package model

import (
	"github.com/bear/wolf/config"
	"gorm.io/gorm"
)

type UserTask struct{
	Id 			int	 `json:"id" `
	TaskId 	int `gorm:"column:task_id"  json:"taskId" `
	UserId     	int `gorm:"column:user_id" json:"userId" `
}

// 自定义表名
func (u *UserTask) TableName() string {
	return "user_task"
}

func DeleteByProjectId(tx *gorm.DB,projectId int) error{
	return tx.Where("task_id = ?",projectId).Delete(&UserTask{}).Error
}
//根据userId 查询taskname
func GetTaskNameByUserIdList(userId int)[]string{
	var userTaskList []UserTask
	config.DB.Where("user_id = ?",userId).Find(&userTaskList)
	if(len(userTaskList) ==0){
		return []string{}
	}
	var taskNames []string
	for _, value := range userTaskList {
		taskname := GetTaskNameById(value.TaskId)
		taskNames = append(taskNames, taskname)
	}
	return taskNames
}

func GetUserNmeByTaskId(taskId int)[]string{
	var userTaskList []UserTask
	config.DB.Where("task_id = ?",taskId).Find(&userTaskList)
	if(len(userTaskList) ==0){
		return []string{}
	}
	var usernames []string
	for _, value := range userTaskList {
		username := GetUserNameById(value.UserId)
		usernames = append(usernames, username)
	}
	return usernames
}

func InsertTaskUser(tx *gorm.DB,taskId int,userIds []int) error{
	var userTasks []UserTask
	for _, v := range userIds {
		userTasks = append(userTasks, UserTask{
			UserId: v,
			TaskId: taskId,
		})
	}
  	if err :=tx.CreateInBatches(userTasks, len(userTasks)).Error; err != nil {
        return err // 返回错误给调用方处理
    }
	return nil
}
